package cn.edu.swu.core;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public abstract class AbstractRepo {
    private static BasicDataSource dataSource;
    static {
        // Create a BasicDataSource object 用于管理数据库连接池
        dataSource = new BasicDataSource();

        // Set the JDBC driver
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

        // Set the database URL
        dataSource.setUrl("jdbc:mysql://localhost:3306/bookstore");

        // Set the database credentials
        dataSource.setUsername("root");
        dataSource.setPassword("zmj410310");

        // Initialize the connection pool with a certain number of connections
        dataSource.setMinIdle(5);
        dataSource.setMaxIdle(10);
        dataSource.setMaxTotal(20);
        dataSource.setInitialSize(5);
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public void query(String sql, ResultSetVisitor visitor) throws SQLException{
        try(Connection connection = getConnection()){
            try(Statement statement = connection.createStatement()){
                ResultSet resultSet = statement.executeQuery(sql);
                while(resultSet.next()){
                    visitor.visit(resultSet);
                }
            }
        }
    }

    public void execute(String sql) throws SQLException {
        try(Connection connection = getConnection()) {
            try(Statement statement = connection.createStatement()) {
                statement.execute(sql);
            }
        }
    }
}